import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:open_source_china/constants/constants.dart';
import 'package:open_source_china/utils/DataUtils.dart';
import 'package:open_source_china/utils/NetUtils.dart';

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  FlutterWebviewPlugin webviewPlugin = FlutterWebviewPlugin();
  bool isLoading = true;

  @override
  void initState() {
    super.initState();
    webviewPlugin.onUrlChanged.listen((url) {
      // TODO:相同的地址会执行两次，bug
      if (mounted) {
        isLoading = false;
        setState(() {});
        if (url != null && url.contains("code=")) {
          String code = url.split("?")[1].split("=")[1].split("&")[0];
          Map<String, dynamic> params = Map();
          params["client_id"] = AppApiConfig.CLIENT_ID;
          params["client_secret"] = AppApiConfig.SECRET_KEY;
          params["grant_type"] = "authorization_code";
          params["redirect_uri"] = AppApiConfig.CALLBACK;
          params["code"] = '$code';
          params["dataType"] = "json";
          NetUtils.post(AppUrls.OAUTH2_TOKEN, params).then((data) async {
            Map<String, dynamic> map = json.decode(data);
            // TODO: 处理bug错误
            if (map["error"] == "400") {
              print("请求出错");
              return;
            }
            if (map != null && map.isNotEmpty) {
              await DataUtils.setLoginInfo(map: map);
              Navigator.pop(context, AppMsg.SUCCESS);
            }
          });
        }
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    webviewPlugin.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Row(
            children: [
              Text("登录开源中国"),
              SizedBox(
                width: 15.0,
              ),
              isLoading ? CupertinoActivityIndicator() : Text("")
            ],
          ),
        ),
        // 请求示例:GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz&redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
        body: WebviewScaffold(
          withZoom: true,
          withJavascript: true,
          withLocalStorage: true,
          url: AppUrls.OAUTH2_AUTHORIZE +
              '?' +
              'response_type=code&client_id=' +
              AppApiConfig.CLIENT_ID +
              '&redirect_uri=' +
              AppApiConfig.CALLBACK,
        ));
  }
}
